/**********买家路由router/customer.js*******/

const express = require('express')
const pool = require('../../pool.js')
const router = express.Router()

/**********正式开始写路由***********/
//0.为分页服务：查询所有记录
//GET /getAll
router.get('/getAll', (req, res) => {
	let sql = 'select id from customer'
	pool.query(sql, (err, result) => {
		if (err) throw err
		res.send(result)
	})
})
//1.声明当前路由器下的接口：买家列表
//GET  /showcoustomers
//参数  pno
//返回数据：查询到的所有买家信息
//测试地址：http://127.0.0.1:端口号/user/showcoustomers
router.get('/showcoustomers', (req, res) => {
	//如果没有传参，设置默认值
	//如果页码为空，设置默认值为1
	if (req.query.pno === undefined) {
		req.query.pno = 1
	}
	//如果每页数据量为空，设置默认值5
	if (req.query.count === undefined) {
		req.query.count = 5
	}
	console.log(req.query)
	//计算开始查询的值
	var start = (req.query.pno - 1) * req.query.count
	//每页数据量转为数值
	var size = parseInt(req.query.count)
	let sql = 'select id,uname,uphone,uemail,u_true_name,ugender,uaddr,isTrue from customer limit ?, ?'
	pool.query(sql, [start, size], (err, result) => {
		if (err) throw err;
		res.send(result)
	})
})
//2.更改买家状态
//put   /changeState
//参数： id
//更新  isTrue:1  正常  isTrue:0  禁用
router.put('/changeState', (req, res) => {
	let sql = `update customer set isTrue=? where id=?`
	let state = req.query.state
	let id = req.query.id
	pool.query(sql, [state, id], (err, result) => {
		if (err) { throw err }
		if (result.affectedRows > 0) {
			res.send({ message: '操作成功！', code: 200 });
		} else {
			res.send({ message: '操作失败！', code: 201 });
		}
	})
})

//导出路由器
module.exports = router
